package com.t216.dm216.serializer;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.filter.Filter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

public class RedisFastJson2Serializer<T> implements RedisSerializer<T> {

    private Class<T> clazz;
    public RedisFastJson2Serializer(Class<T> clazz) {
        this.clazz = clazz;
    }
    /*我们不是说 我们的这个封装必须和Jackson提供的封装写的一样 没有这个规矩 是我们自己编写的 你想怎么写 就怎么写*/
    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (t == null) {
            return new byte[0];
        }else{
            try {
                return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName).getBytes("utf-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
    }


    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        String str = new String(bytes, Charset.forName("utf-8"));
        return JSON.parseObject(str,clazz, JSONReader.autoTypeFilter("com.t216.dm216"));
    }
}
